﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.SqlClient;
using System.Data;
using EasyLib.Extensions;

namespace EasyLib.Configuration
{
    /// <summary>
    /// class extends from AbstractConfig, which will load data from db
    /// </summary>
    public class DatabaseConfig : DefaultConfig
    {
        private const string SELECT_SQL = "SELECT KEY_X, VALUE_X, CAT_X FROM {0}";

        public string ConnectionString { get; set; }

        public string TableName { get; set; }

        internal protected DatabaseConfig(string tableName, string connectionString)
        {
            ConnectionString = connectionString;
            TableName = tableName;
        }

        /// <summary>
        /// override method, load config items from database
        /// </summary>
        public override void LoadData()
        {
            try
            {
                using (SqlConnection conn = new SqlConnection(ConnectionString))
                {
                    conn.Open();
                    DataTable dt = new DataTable();
                    string sql = string.Format(SELECT_SQL, TableName);
                    SqlDataAdapter da = new SqlDataAdapter(sql, conn);
                    da.Fill(dt);

                    foreach (DataRow dr in dt.Rows)
                    {
                        string key = (dr["KEY_X"] as string).Null2Blank();
                        string value = (dr["VALUE_X"] as string).Null2Blank();
                        string category = (dr["CAT_X"] as string).Null2Blank();
                        if (ConfigUtils.Cache.Keys.Contains<string>(category))
                        {
                            IDictionary<string, string> items = ConfigUtils.Cache[category];
                            items.Add(key, value);
                        }
                        else
                        {
                            IDictionary<string, string> items = new Dictionary<string, string>();
                            items.Add(key, value);
                            ConfigUtils.Cache[category] = items;
                        }
                    }
                }
            }
            catch (Exception)
            {
                //TODO
            }
        }
    }
}